package com.maple.controller.alipay;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayUploadRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.maple.properties.AlipayProperties;
import com.maple.result.Result;
import com.maple.service.PayNotifyService;
import com.maple.utils.AlipayUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/notify")
public class PayNotifyController {

    @Autowired
    private PayNotifyService payNotifyService;

    @Autowired
    private AlipayProperties alipayProperties;


    /**
     * 支付成功的异步请求
     * @param request
     * @param response
     * @return
     * @throws AlipayApiException
     */
    @PostMapping("/paySuccess")
    public String paySuccess(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
        log.info("支付成功的异步请求");
        Map<String, String> params = AlipayUtils.paySuccess(request, response);

        boolean flag = AlipaySignature.rsaCheckV1(params,
                alipayProperties.getAlipayPublicKey(),
                alipayProperties.getCharset(),"RSA2");

        // 签名验证校验
        if (!flag) {
            return "FAIL";
        }

        if (payNotifyService.paySuccess(params)) {
            return "success";
        } else {
            return "fail";
        }

    }



}
